﻿
using Ec.NETCoreFramework.Common;
using Ec.NETCoreFramework.Common.Core.Helpers;
using Ec.NETCoreFramework.Common.Core.Serializer;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Ec.NETCoreFramework.Common.Cache
{
    /// <summary>
    /// redis操作
    /// </summary>
    public class RedisListService : RedisDataBaseManager
    {
        public RedisListService(string server, string password, int dbId) : base(server, password, dbId)
        {

        }     
        /// <summary>
        /// 在列表尾部插入值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="data"></param>
        public void ListRightPush<T>(string key, T data)
        {
            if (_Database == null||string.IsNullOrEmpty(key)) return;
            try
            {
                byte[] bytes = ByteSerializer.Serialize(data);
                _Database.ListRightPush(key, bytes);
            }
            catch (Exception ex)
            {
                LoggerHelper.Instance.Error("Cache-Redis" + ex.Message);
            }

  
        }
        /// <summary>
        /// 移除并返回存储在key对应列表的第一个元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T ListLeftPop<T>(string key)
        {
            //默认值
            var value = default(T);
            if (_Database == null || string.IsNullOrEmpty(key)) return value;
            try
            {
                var cacheValue=_Database.ListLeftPop(key);
                if (!cacheValue.IsNull)
                {
                    byte[] bytes = (byte[])cacheValue;

                    if (bytes != null && bytes.Length > 0)
                    {
                        value = ByteSerializer.Deserialize<T>(bytes);
                    }
                    return value;
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Instance.Error("Cache-Redis"+ex.Message);
            }

            return value;
        }
        /// <summary>
        /// list 是否存在
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool IsExitList(string key)
        {
            if (_Database == null || string.IsNullOrEmpty(key)) return false;
            return _Database.ListLength(key)>0;
        }

    }
}
